﻿using DG.Tweening;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

public class TalentPanel : MonoBehaviour
{
    [SerializeField]
    private List<RectTransform> contents;            // 所有滚动内容
    [SerializeField]
    private List<GameObject> lastButtons;            // 每个 content 对应的最后一个按钮
    [SerializeField]
    private List<Sprite> changeSprites;              // 每个按钮要变成的图片
    [SerializeField]
    private Sprite originalButtonSprite;             // 原始按钮图片
    [SerializeField]
    private float scrollSpeed = 500f;                // 滚动速度（像素/秒）

    private List<Vector2> originalPositions = new List<Vector2>();// 存储原始位置（anchoredPosition）
    private List<float> endOffsets = new List<float>();// 存储每个 content 的最终偏移
    [SerializeField]
    private Dictionary<Sprite, UnityAction> talentDic = new Dictionary<Sprite, UnityAction>();// sprite 和 按钮点击事件
    

    /*    private void OnEnable()
        {
            originalPositions.Clear();
            endOffsets.Clear();

            for (int i = 0; i < contents.Count; i++)
            {
                RectTransform content = contents[i];
                RectTransform lastBtnRect = lastButtons[i].GetComponent<RectTransform>();

                Vector2 originalPos = content.anchoredPosition;
                originalPositions.Add(originalPos);

                float contentHeight = content.rect.height;
                float lastBtnHeight = lastBtnRect.rect.height;
                float endOffset = contentHeight - lastBtnHeight;

                endOffsets.Add(endOffset);

                StartCoroutine(Scroll(content, lastButtons[i], originalPos, endOffset, changeSprites[i], i));
                //Scroll(content, lastButtons[i], originalPos, endOffset, changeSprites[i], i + 1);
            }
        }*/

    private void Awake()
    {
        talentDic.Add(changeSprites[0], OnUpAttackButtonClick);
        talentDic.Add(changeSprites[1], OnUpHpButtonClick);
    }

    private void OnEnable()
    {
        //设置到canvase的最下层
        transform.SetAsLastSibling();
        originalPositions.Clear();
        endOffsets.Clear();

        //随机生成数字
        int count = talentDic.Count;
        List<int> indices = Enumerable.Range(0, count).ToList(); // [0, 1, 2, ..., count-1]
        List<int> randomIndices = indices.OrderBy(x => UnityEngine.Random.value).Take(count).ToList();


        for (int i = 0; i < contents.Count; i++)
        {
            RectTransform content = contents[i];
            RectTransform lastBtnRect = lastButtons[i].GetComponent<RectTransform>();

            Vector2 originalPos = content.anchoredPosition;
            originalPositions.Add(originalPos);

            float contentHeight = content.rect.height;
            float lastBtnHeight = lastBtnRect.rect.height;
            float endOffset = contentHeight - lastBtnHeight;

            endOffsets.Add(endOffset);

            int loopCount = i + 1; // 第1个滚1次，第2个滚2次...


            StartCoroutine(Scroll(content, lastButtons[i], originalPos, endOffset, changeSprites[randomIndices[i]], loopCount));
        }
    }




    private void OnDisable()
    {
        // 恢复原始位置和按钮图片
        for (int i = 0; i < contents.Count; i++)
        {
            contents[i].anchoredPosition = originalPositions[i];
            lastButtons[i].GetComponent<Image>().sprite = originalButtonSprite;
        }
    }
    /*    /// <summary>
        /// 滚动内容并替换按钮图片
        /// </summary>
        /// <param name="content"></param>
        /// <param name="lastButton"></param>
        /// <param name="originalPos"></param>
        /// <param name="endOffset"></param>
        /// <param name="changeSprite"></param>
        private void Scroll(RectTransform content, GameObject lastButton, Vector2 originalPos, float endOffset, Sprite changeSprite)
        {
            float distance = Mathf.Abs(endOffset - originalPos.y);// 计算滚动距离
            float duration = distance / scrollSpeed;// 计算滚动持续时间

            // 替换按钮图片
            lastButton.GetComponent<Image>().sprite = changeSprite;

            //TODO: 给lastButton添加点击事件

            // 滚动动画
            DOTween.To(
                () => content.anchoredPosition,
                value => content.anchoredPosition = value,
                new Vector2(originalPos.x, endOffset),
                duration
            ).SetEase(Ease.OutCubic);
        }*/

    /// <summary>
    /// 滚动内容并替换按钮图片（支持多次循环滚动）
    /// </summary>
    IEnumerator Scroll(RectTransform content, GameObject lastButton, Vector2 originalPos, float endOffset, Sprite changeSprite, int loopCount)
    {
        float distance = Mathf.Abs(endOffset - originalPos.y);
        float duration = distance / scrollSpeed;

        for (int i = 0; i < loopCount - 1; i++)
        {
            yield return content.DOAnchorPos(new Vector2(originalPos.x, endOffset), duration)
                                .SetEase(Ease.Linear)
                                .SetUpdate(true) // ✅ 关键！不受 Time.timeScale影响
                                .WaitForCompletion();

            content.anchoredPosition = originalPos;
        }

        if (changeSprite != null)
        {
            lastButton.GetComponent<Image>().sprite = changeSprite;
            lastButton.GetComponent<Button>().onClick.AddListener(talentDic[changeSprite]);
        }
        // 最后一圈（停下）
        yield return content.DOAnchorPos(new Vector2(originalPos.x, endOffset), duration)
                            .SetEase(Ease.OutCubic)
                            .SetUpdate(true) // ✅ 关键！不受 Time.timeScale影响
                            .WaitForCompletion();

    }


    #region 按钮事件

    /// <summary>
    /// 点击之后给玩家攻击速度提升
    /// </summary>
    public void OnUpAttackButtonClick()
    {
        Debug.Log("攻击速度提升");
        Player.Player.instance.SetAttackCoolDown(-0.1f);
        Time.timeScale = 1f;
        gameObject.SetActive(false);
    }

    /// <summary>
    /// 玩家增加血量
    /// </summary>
    public void OnUpHpButtonClick()
    {
        Debug.Log("增加血量");
        Player.Player.instance.AddHp(20);
        Time.timeScale = 1f;
        gameObject.SetActive(false);
    }

    #endregion



}
